<?php
// +----------------------------------------------------------------------
//// | ThinkPHP [ WE CAN DO IT JUST THINK ]
//// +----------------------------------------------------------------------
//// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
//// +----------------------------------------------------------------------
//// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
//// +----------------------------------------------------------------------
//// | Author: 流年 <liu21st@gmail.com>
//// +----------------------------------------------------------------------
//
//// 应用公共文件
use \think\Image;
use \think\Cache;
use app\model\Version;
/**
 * 上传单个图片
 * @param string $size
 * @param string $ext
 * @param string $width
 * @param string $file
 * @param string $height
 * @return array status=>状态 message=>错误或路径
 */
function uploadImageOne($fileName,$size='1',$ext='jpg,png,gif,jpeg',$path='./uploads',$width='1024',$height='1024'){
    $file=request()->file($fileName);
    if(empty($file)){
        return ['status'=>2,'message'=>"请上传图片"];
    }
    $size=$size*1024*1024;
    $info=$file->validate(['size'=>$size,'ext'=>$ext])->move($path);
    if($info){
        $saveName=DIRECTORY_SEPARATOR."uploads".DIRECTORY_SEPARATOR.$info->getSaveName();
        $saveName1=".".DIRECTORY_SEPARATOR."uploads".DIRECTORY_SEPARATOR.$info->getSaveName();
        $image=Image::open($saveName1);
        $image->thumb($width,$height)->save($saveName1);
        return ['status'=>0,'message'=>'http://'.$_SERVER['HTTP_HOST'].$saveName];

    }else{
        return ['status'=>1,'message'=>$file->getError()];
    }

}

/**
 * 返回json
 * @param $code
 * @param string $msg
 * @param array $data
 * @return json
 */
function return_json($code='',$msg='',$data=array()){
    $arr = array(
        'code' => $code,
        'msg' =>$msg
    );
    $arr['data'] = $data;
    json($arr,200, ['Access-Control-Allow-Origin'=> '*','Access-Control-Allow-Headers'=>'content-type,token,x-requested-with','Access-Control-Expose-Headers'=>'*','Access-Control-Allow-Methods'=>"GET,POST,PUT,DELETE,PATCH,OPTIONS"])->send();
    exit;
}


/**
 * 公共日志函数
 * @param $uid
 * @param $username
 * @param string $action
 * @param string $datas
 */
function dolog($uid, $username, $action='', $datas=''){

    //插入记录到日志
    $time = time();
    \app\model\Adminlog::create([
        'uid'=>$uid,
        'username'=>$username,
        'action'=>$action,
        'datas'=>$datas,
        'ctime'=>$time
    ]);
}

/**
 * 加密公共函数
 */
function encrypt_md5($param="",$key=""){
    if(is_array($param)){
        $md5Str = implode(arrSort($param));
    }
    else{
        $md5Str = $param;
    }
    $md5 = md5($md5Str . $key);
    return '' === $param ? 'false' : $md5;
}

/**
 * 键值升序排列
 */
function arrSort($para)
{
    reset($para);
    ksort($para);
    return $para;
}

/**
 * 发送短信API
 * @param:phone 电话号码
 * @return $code 验证码
 */
function sendSms($phone=''){

    $user_id =  \app\model\Userinfo::where('phone', $phone)->column('id');
    if($user_id)
    {
        return_json(0, '您已经注册过了');
    }

//    $key = 'phdyw'.$phone;           //设置key值
//    $memcache_obj = get_memcached();
//    $code = $memcache_obj->get($key);          //去缓存中获取key值
//    if($code)
//    {
//        return_json(1,'验证码未使用');
//    }else{
//        $code = rand(100000,900000);
//    }
    $code = rand(100000,900000);
    $sms_tpl_id = config('sms.SMS_TPL_ID');      //获取短信模板id
    $tpl_value = "#code#=$code";
    $res = json_decode(send_sms($sms_tpl_id, $tpl_value, $phone),true);
    if($res['code'] == 33){
        return_json(0,'短信次数已达上限');
    }
//    dump($res);exit;
    if($res['code'] == 0 && $res['msg'] == 'OK')
    {
        //短信发送成功时,将短信存入memcahce
//        $memcache_obj->set($key,$code,86400);
        return_json(1,'短信发送成功');
    }else{
        return_json(0,'短信发送失败');
    }
}

function send_sms($tpl_id, $tpl_value, $phone){
    $url="http://yunpian.com/v1/sms/tpl_send.json";
    $encoded_tpl_value = urlencode("$tpl_value");
    $phone = urlencode("$phone");
    $post_string="apikey=".config('yp.YPKEY')."&tpl_id=$tpl_id&tpl_value=$encoded_tpl_value&mobile=$phone";
    return sock_post($url, $post_string);
}

/**
 * 验证验证码是否过期
 */
function check_smscode($phone,$code)
{
    $key = 'phdyw'.$phone;
    $memcache_obj = get_memcached(0);
    $cache_code = $memcache_obj->get($key);
    if(!$cache_code){
        return_json(0,'验证码不存在');
    }

    if ($cache_code != $code) {
        return_json(0,'验证码不正确');
    }
}


function sock_post($url,$query){
    $data = "";
    $info=parse_url($url);
    $fp=stream_socket_client($info["host"].':80',$errno,$errstr,30);
    if(!$fp){
        return $data;
    }
    $head="POST ".$info['path']." HTTP/1.0\r\n";
    $head.="Host: ".$info['host']."\r\n";
    $head.="Referer: http://".$info['host'].$info['path']."\r\n";
    $head.="content-type: application/x-www-form-urlencoded\r\n";
    $head.="content-Length: ".strlen(trim($query))."\r\n";
    $head.="\r\n";
    $head.=trim($query);
    $write=fputs($fp,$head);
    $header = "";
    while ($str = trim(fgets($fp,4096))) {
        $header.=$str;
    }
    while (!feof($fp)) {
        $data .= fgets($fp,4096);
    }
    return $data;
}

/**
 * 获取登录Ip
 * @return mixed
 */
function getip()
{
    $ip = false;
    if(!empty( $_SERVER ["HTTP_CLIENT_IP"]))
    {
        $ip = $_SERVER ["HTTP_CLIENT_IP"];
    }
    if (!empty( $_SERVER ['HTTP_X_FORWARDED_FOR']))
    {
        $ips = explode ( ", ",$_SERVER ['HTTP_X_FORWARDED_FOR']);
        if ($ip)
        {
            array_unshift ($ips,$ip);
            $ip = FALSE;
        }
        for($i = 0; $i < count ( $ips ); $i ++)
        {
            if (!preg_match( "/^(10|172\.16|192\.168)\./",$ips[$i]))
            {
                $ip =$ips[$i];
                break;
            }
        }
    }
    $ip_str=($ip?$ip:$_SERVER['REMOTE_ADDR']);
    $ip_arr=explode(',',$ip_str);
    return $ip_arr[0];
}

//获取省份
function getArea($ip)
{
    //$ip = getIp();
    $res1 = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=$ip");
    //dp($res1);
    $res1 = json_decode($res1,true);


    if ($res1[ "code"]==0)
    {
        return $res1['data']["country"].$res1['data'][ "region"].$res1['data']["city"]."_".$res1['data'][ "isp"];
    }else{
        return "未知";
    }
}

# 生成随机字符串
function randomkeys($length){
    $key = null;
    $pattern = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ";
    for($i = 0; $i < $length; $i ++)
    {
        $key .= $pattern {mt_rand ( 0, 35 )};
    }
    return $key;
}

//版本控制接口(前台使用)
function check_version()
{
    //获取基本参数
    $headers = request()->header();
    if (empty($headers['ver']) || empty($headers['pt'])) {

        return_json(0, '缺少参数');
    }
    //app传过来的版本号
    $ver = $headers['ver'];

    //查询当前版本
    $res = Version::where('appid', $headers['appid'])->where('pt', $headers['pt'])->order('id', 'desc')->limit(1)->find();

    //当前版本号
    $current_ver = $res['version_code'];

    //发布版本号
    $release_ver = $res['release_code'];

    if($headers['pt']==1){
       $res = Version::where('pt',1)->find();
    }else{
        //    检测app版本是否小于服务端当前版本
        if (version_compare($ver, $release_ver, '=')) {
            $res['is_release'] = 1;

        } else {
            $res['is_release'] = 0;
            if (version_compare($ver, $current_ver, '<')) {
                $res['is_update'] = $res->update_type;
            }
        }
    }

    return_json(1, '更新信息', $res);

}


//版本控制接口(后台使用)
function check(){
    $headers = request()->header();
//app传过来的版本号
    $ver = $headers['ver'];
//查询当前版本
    $res = Version::where('appid',$headers['appid'])->where('pt',$headers['pt'])->order('id','desc')->limit(1)->find();

//         //当前版本号
//         $current_ver = $res['version_code'];

//发布版本号
    $release_ver = $res['release_code'];

//    检测app版本是否小于服务端当前版本
    if(version_compare($ver,$release_ver,'=')){
        return 0;
    }else{
        return 1;
    }
}

//获取时间差
function time_z($time){
    $now = time();
    $m = $now-$time;
    if($m <=60){
        return '刚刚';
    }elseif ($m>10 && $m<3600) {
        $num_=floor($m/60);
        return $num_.'分钟前';
    }elseif ($m>=3600 && $m<86400) {
        $num_=floor($m/3600);
        return $num_.'小时前';
    }else{
        return date('Y-m-d',$time);
    }
}

//根据时间戳获取星期
function weekday($time)
{
    if(is_numeric($time))
    {
        $weekday = array('星期日','星期一','星期二','星期三','星期四','星期五','星期六');
        return $weekday[date('w', $time)];
    }
    return false;
}

/**
 * 用户操作金额记录
 * @param: uid 用户id
 * @param amount 收支金额
 * @param r_name 收支类型
 * @param r_type 收支 1:支出 | 2:收入
 * @param yu_e 用户操作前总余额
 */

function operation($uid,$amount,$r_name,$r_type,$yu_e,$match_id=0){
    //插入记录
    $time = time();
    \app\model\CionRecords::create([
        'uid'=>$uid,
        'amount'=>$amount,
        'r_name'=>$r_name,
        'r_type'=>$r_type,
        'ctime'=>$time,
        'match_id'=>$match_id,
        'yu_e'=>$yu_e
    ]);
}


/**
 * @param array $list
 * @param int $parent_id
 * @param int $deep
 * @return array
 * 无限极分类
 */
function infinite($list = [],$parent_id = 0,$deep = 0)
{
    static $arr = [];
    foreach ($list as $v)
    {
        if($v['p_id'] == $parent_id)
        {
            $v['deep'] = $deep;
            $arr[] = $v;
            infinite($list,$v['id'],$deep + 1);
        }
    }
    return $arr;
}
